import db from '@/utils/sessionstorage'
const state = () => ({
  list: db.get('process', '') || [{
    label: '首页',
    value: '/dashboard',
    noCache: 0,
    active: true,
    name: 'Layout',
  }, ],
})

const mutations = {
  addProcess(state, item) {
    const index = state.list.findIndex(
      (e) => e.value.split('?')[0] === item.value.split('?')[0]
    )

    state.list.map((e) => {
      e.active = e.value === item.value
    })

    if (item.value === '/dashboard') {
      item.label = '首页'
      item.name = 'Layout'
      item.value = '/dashboard'
      item.noCache = 0
      item.active = true
    }

    if (index < 0) {
      if (item.label) {
        state.list.push({
          ...item,
          active: true,
        })
      }
    } else {
      state.list[index].active = true
      state.list[index].noCache = item.noCache || false
      state.list[index].label = item.label
      state.list[index].value = item.value
      state.list[index].name = item.name
    }
    db.save('process', state.list)
  },
  
  delProcess(state, index) {
    state.list.splice(index, 1)
    db.save('process', state.list)
  },

  setProcess(state, list) {
    state.list = list
    db.save('process', list)
  },

  resetProcess(state) {
    state.list = [{
      label: '首页',
      value: '/dashboard',
      noCache: 0,
      active: true,
      name: 'Layout',
    } ]
    db.save('process', state.list)
  },
}

const actions = {
  async delView({ commit, state }, view){
    return new Promise(resolve => {
      const index = state.list.findIndex(e => e.name === view.name )
      commit('delProcess', index)
      resolve(state.list)
    })
  }
}

export default {
  namespaced: true,
  state: state,
  actions: actions,
  mutations: mutations,
}